import messageApi from '@/services/api/msg.js'
import {
		v4 as uuidv4
	} from 'uuid';
import sqliteFriend from '@/sqlite_services/friend.js'
import friendsApi from "@/services/api/friends.js"
import $store from '@/store/index.js';
const syczuanNotice = uni.requireNativePlugin("syczuan-notice");
class TUICallKitManager {
  constructor() {
    if (TUICallKitManager.instance) {
      return TUICallKitManager.instance;
    }

    this.TUICallKit = uni.requireNativePlugin('TencentCloud-TUICallKit');
    this.TUICallKitEvent = uni.requireNativePlugin('globalEvent');
    this.currentUser = null;              // 当前登录用户的信息
	
    this.currentCallUserID = null;        // 当前通话的用户ID
	this.callMediaType = 0 //当前通话的类型
    this.isInitiator = false;             // 标记是否是主动发起的通话
	this.isSwitchon = false;             // 标记是否接通
	this.isCanceledByCaller = false // 取消标记 判断主动取消使用
	
	this.roomID = 0
    // 保存实例
    TUICallKitManager.instance = this;
  }

  // 初始化 CallKit
  init(userInfo) {
    return new Promise((resolve, reject) => {
      this.currentUser = {
        userID: userInfo.user_id,
        userSig: userInfo.userSig
      };
	  console.log(userInfo);
      const options = {
        SDKAppID: uni.$config.trtc_appid && Number(uni.$config.trtc_appid),
        userID: this.currentUser.userID,
        userSig: this.currentUser.userSig
      };
	  console.log('TUICallKitoptions',options);
      this.TUICallKit.login(options, async (res) => {
		  console.log(res);
        if (res.code === 0) {
          this.handleMonitor();
          this.TUICallKit.enableFloatWindow(true);
          resolve();
        } else {
          reject(res.msg);
        }
      });
    });
  }

  // 拨打电话
  dial(user_id, type) {
    return new Promise(async (resolve, reject) => {
      uni.showLoading({
        title: getApp().$t("api.loading.user.loading")
      });

      this.currentCallUserID = user_id; // 记录当前通话用户ID
      this.isInitiator = true;          // 标记为主动发起
	  this.isCanceledByCaller = false;    // 重置取消标记
	  this.callMediaType = type
	  this.isSwitchon = false //重置为未接通
	  
      const options = {
        userID: user_id,
        callMediaType: type
      };

      this.TUICallKit.call(options, (res) => {
		  console.log(res);
        uni.hideLoading();
        if (res.code === 0) {
          resolve();
        } else {
		  uni.showToast({
		  	title:res.msg,
			icon:'none'
		  })
          reject(res.msg);
        }
      });
    });
  }

  // 设置用户信息
  setInfo(nick_name, avatar_url) {
    return new Promise((resolve, reject) => {
	  let data= {}
	  if(nick_name){
		  data.nickName=nick_name
	  }
	  if(avatar_url){
		  data.avatar=avatar_url
	  }
      this.TUICallKit.setSelfInfo(data, (res) => {
		  console.log('shezhiyuyintonghua',res);
        if (res.code === 0) {
          resolve();
        } else {
          reject(res.msg);
        }
      });
    });
  }

  // 监听事件
  handleMonitor() {
    this.TUICallKitEvent.addEventListener('onError', (res) => {
      console.log('onError', JSON.stringify(res));
    });
	//取消的回调
    this.TUICallKitEvent.addEventListener('onCallCancelled', (res) => {
	  setTimeout(()=>{
		  if (this.isInitiator && !this.isCanceledByCaller && !this.isSwitchon) {
			  let msg_type = this.callMediaType == 1?'voice_call':'video_call'
			  let content_text = [{
					  [msg_type]:{
						  call_type:0,//主动取消
						  duration:0
					  }
			  }]
			  this.directsend(this.currentCallUserID,msg_type,content_text,'private')
		  }else if(this.isInitiator && !this.isCanceledByCaller && this.isSwitchon){
		  	  let msg_type = this.callMediaType == 1?'voice_call':'video_call'
		  	  let content_text = [{
				  [msg_type]:{
					  call_type:5,//异常中断
					  duration:0
				  }
		  	  }]
		  	  this.directsend(this.currentCallUserID,msg_type,content_text,'private')
		  }
		  this.clearCallData(); // 通话取消时清除通话数据
	  },50)	
    });
	//电话接通的回调
	this.TUICallKitEvent.addEventListener('onCallBegin', (res) => {
		this.isSwitchon = true
		this.roomID = res.roomID
	   console.log('onCallBegin',res);
	});
	//通话请求的回调
	this.TUICallKitEvent.addEventListener('onCallReceived', async(resCall) => {
	   console.log('onCallReceived',resCall);
	   try{
		   console.log(123123132);
			let chatinfo = null
			let res = await sqliteFriend.getUserInfo(resCall.callerId)
			if (res) {
				chatinfo = res
			}else{
				//网络请求并更新用户表
				let apires = await friendsApi.getFriendInfo(resCall.callerId)
				if(apires){
					chatinfo = apires
				}
			}
			console.log(chatinfo);
			if(chatinfo){
				let myid = $store.state.user.user_info.user_id
				let notif = myid+'notif'
				let notifsStorage = uni.getStorageSync(notif)
				if(notifsStorage){
					notifsStorage = JSON.parse(notifsStorage)
				}
				if(!uni.$appShow && !chatinfo.disturbing && !notifsStorage.disturb  && !notifsStorage.stopNewMsg){
					this.linePush(chatinfo,notifsStorage,resCall.callMediaType)
				}
			}
	   }catch(e){
		   console.log(e);
	   	//TODO handle the exception
	   }
	   
	});
	//通过结束
	﻿this.TUICallKitEvent.addEventListener('onCallEnd', (res) => {
	  console.log('onCallEnd', JSON.stringify(res));
	  if(res.callRole == 1){
		  let msg_type = res.callMediaType == 1?'voice_call':'video_call'
		  let content_text = [{
			  [msg_type]:{
				  call_type:1,
				  duration:res.totalTime
			  }
		  }]
		  this.directsend(this.currentCallUserID,msg_type,content_text,'private')
	  }
	  this.clearCallData(); // 通话取消时清除通话数据
	});
	
    this.TUICallKitEvent.addEventListener('onUserLineBusy', (res) => {
	   this.isCanceledByCaller = true  //打上标记证明不可能是主动取消了
	   let msg_type = this.callMediaType == 1?'voice_call':'video_call'
	   let content_text = [{
			  [msg_type]:{
				  call_type:4,//忙线中
				  duration:0
			  }
	    }]
		this.directsend(this.currentCallUserID,msg_type,content_text,'private')
      console.log('onUserLineBusy', JSON.stringify(res));
    });

    this.TUICallKitEvent.addEventListener('onUserNoResponse', (res) => {
		this.isCanceledByCaller = true  //打上标记证明不可能是主动取消了
		let msg_type = this.callMediaType == 1?'voice_call':'video_call'
		let content_text = [{
			  [msg_type]:{
				  call_type:3,//未响应
				  duration:0
			  }
		}]
		this.directsend(this.currentCallUserID,msg_type,content_text,'private')
      console.log('onUserNoResponse', JSON.stringify(res));
    });
	// 通话被拒绝时清除通话数据
    this.TUICallKitEvent.addEventListener('onUserReject', (res) => {
		this.isCanceledByCaller = true  //打上标记证明不可能是主动取消了
		let msg_type = this.callMediaType == 1?'voice_call':'video_call'
		let content_text = [{
			  [msg_type]:{
				  call_type:2,//拒绝
				  duration:0
			  }
		}]
		this.directsend(this.currentCallUserID,msg_type,content_text,'private')
      console.log('onUserReject', JSON.stringify(res));
    });

    // 监听来电事件
    this.TUICallKitEvent.addEventListener('onIncomingCall', (res) => {
      this.currentCallUserID = res.userID; // 设置来电的用户ID
      this.isInitiator = false;            // 标记为被动接听
      console.log('Incoming call from', res.userID);
    });
  }
  //发送消息
  async directsend(uuid,msg_type,content_text,chat_type){
  	try {
  		let wy_id = uuidv4();
  		let resmsg = await messageApi.directsend({
  			target_id: uuid,
  			local_id: wy_id,
  			msg_type: msg_type,
  			content_text: content_text
  		},chat_type);
  	} catch (e) {
  		console.log(e);
  	}
  }
  
  //在线后台推送
  linePush(data,notifsStorage,type){
  	if(notifsStorage.stopNewMsg)return
  	// 发送通知
	console.log(data.user_id);
  	 syczuanNotice.send(
  	   {
  		 noticeId:Number(data.user_id),
  		 // 通知标题
  		 title: data.friend_remark || data.nick_name,
  		 // 通知内容
  		 content: type == '1'?getApp().$t("chat.msg.type.invitationVoice"):getApp().$t("chat.msg.type.invitationVideo"),
  		 // 大图标
  		 largeIcon: false,
  		 // 点击是否自动关闭通知
  		 autoCancel: true,
  		 // 毫秒时间戳 默认显示当前时间
  		 noticeTime: true,
  		 // 通知优先级
  		 import: 0,
  		 // 未读通知数 0不显示
  		 badge: 0,
  		 // 通知长文本
  		 bigText: "",
  		 // 自定义数据
  		 payload: {
  		   data:data
  		 },
  	   },
  	   (e) => {
  		 console.log(e);
  	   }
  	 );
  }

  // 清除通话数据
  clearCallData() {
	this.isCanceledByCaller = false  //打上标记证明不可能是主动取消了
    this.currentCallUserID = null;
    this.isInitiator = false;
	this.isSwitchon = false;
	this.roomID = 0
	this.callMediaType = 0
  }
}

// 导出单例实例
const tuicallKitManagerInstance = new TUICallKitManager();
export default tuicallKitManagerInstance;
